<?php


namespace App\Service\api;


use App\Common\RedisUtils;
use App\Common\Res;
use App\Common\SendMsgUtils;
use App\Common\SendTalkMsgUtils;
use App\Common\StringUtils;
use App\Constants\ConstCode;
use App\Constants\ErrorCode;
use App\Model\form\AttachmentTrait;
use App\Model\form\MessageTalkTrait;
use App\Model\form\WeworkAccountTrait;
use App\Model\form\WeworkFriendTrait;
use App\Request\client\WeworkFriendRequest;
use Hyperf\Context\Context;
use Hyperf\DbConnection\Db;
use Hyperf\Utils\ApplicationContext;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
use Hyperf\Config\Annotation\Value;
use Psr\Http\Message\ServerRequestInterface;

class operationService
{
    use StringUtils, Res, RedisUtils,
        SendMsgUtils, WeworkAccountTrait, AttachmentTrait,
        MessageTalkTrait, WeworkFriendTrait, SendTalkMsgUtils;

    /**
     * @Value("commonset.hostUrl")
     */
    protected $hostUrl;

    /**
     * 聊天页面心跳
     * @param int $fd
     * @return array
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function getOperationPop(int $fd): array
    {
        $login = $this->getChat(ConstCode::CHAT_TOKEN . $fd);
        if (!empty($login)) {
            $login = $this->setChat(ConstCode::CHAT_TOKEN . $fd, $login, 100);
            $data['code'] = ErrorCode::SUCCESS;
            $data['msg'] = '心跳成功';
        } else {
            $data['code'] = ErrorCode::ERROR;
            $data['msg'] = '心跳失败';
        }
        return $data;
    }

    /**
     * 聊天页获取客服列表
     * @param array $params
     * @return array
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function appOperationList(array $params): array
    {
        try {
            $user = Context::get(ServerRequestInterface::class)->getAttribute('user');
            $userArr = json_decode($user, true);
            $data['data']['nickName'] = $userArr['nickname'];
            $data['data']['userName'] = $userArr['username'];
            $data['data']['userId'] = $userArr['id'];
            $where = function ($query) use ($userArr) {
                $query->where('user_id', $userArr['id']);
                $query->where('status', ConstCode::IS_USE);
            };
            $listArr = $this->getWeworkAccountList($where);
            $list = [];
            if (!empty($listArr)) {
                foreach ($listArr as $key => $value) {
                    $list[$key]['avatarUrl'] = !empty($value['avatar']) ? $this->hostUrl . $value['avatar'] : '';
                    $list[$key]['loginStatus'] = $value['is_login'];
                    $list[$key]['mobile'] = $value['mobile'];
                    $list[$key]['nickname'] = $value['alias_name'];
                    $list[$key]['marketUserType'] = 0;
                    $list[$key]['projectId'] = $value['project_id'];
                    $list[$key]['readableCount'] = $this->getMessageTalkCount(['account_id' => $value['id'], 'is_send' => ConstCode::IS_SEND, 'readable' => 0, 'direction' => 1]);
                    $list[$key]['marketUserId'] = $value['marketUserId'];
                }
            }
            $data['code'] = ErrorCode::SUCCESS;
            $data['data']['workerlist'] = $list;
            $data['msg'] = '操作成功';
            return $data;
        } catch (\Throwable $ex) {
            $data['code'] = ErrorCode::ERROR;
            $data['msg'] = '操作失败';
            $data['data']['workerlist'] = [];
            return $data;
        }
    }


    /**
     * 获取运营号联系人列表
     * @param array $params
     * @return array
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function getContactsList(array $params): array
    {
        ApplicationContext::getContainer()->get(WeworkFriendRequest::class)->validated($params, 'getContactsList');
        $data['total'] = 0;
        $rows = [];
        try {
            $account = $this->getWeworkAccount(['marketUserId' => $params['userId']]);
            if (!empty($account)) {
                $where = function ($query) use ($params, $account) {
                    $query->where('account_id', $account['id']);
                    if (trim($params['nickName']) != null)
                        $query->where('nickname', 'like', '%' . $params['nickName'] . '%');
                };
                $friendPage = $this->getWeworkFriendPage($where, $params);
                if (!empty($friendPage['list'])) {
                    foreach ($friendPage['list'] as $key => $value) {
                        $rows[$key]['avatarUrl'] = !empty($value['path']) ? $this->hostUrl . $value['path'] : '';
                        $rows[$key]['remark'] = $value['remark'];
                        $rows[$key]['userId'] = $value['userId'];
                        $rows[$key]['userNickName'] = !empty($value['nickname']) ? $value['nickname'] : $value['bookname'];
                    }
                    $data['total'] = $friendPage['count'];
                }
            }
            $data['msg'] = '查询成功';
            $data['code'] = ErrorCode::SUCCESS;
            $data['rows'] = $rows;
            return $data;
        } catch (\Throwable $ex) {
            $data['msg'] = '查询失败';
            $data['code'] = ErrorCode::ERROR;
            $data['rows'] = [];
            return $data;
        }
    }


    /**
     * 切换运营者身份
     * @param array $params
     * @return array
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function getChangeMarketUser($fd, array $params): array
    {

        // ApplicationContext::getContainer()->get(MessageRequest::class)->validated($params, 'getChangeOperation');
        try {
            $data['commandType'] = 0;
            $result = $this->sendMessageTalk($fd, $data);
            Db::commit();
            return $this->Success('切换聊天账号成功', $result);
        } catch (\Throwable $ex) {
            Db::rollBack();
            $data['code'] = ErrorCode::ERROR;
            $data['msg'] = $ex->getMessage();
            $result = $this->sendMessageTalk($fd, $data);
            return $this->Error(ErrorCode::ERROR, '切换聊天账号失败' . $ex->getMessage());
        }
    }


}